<?php

namespace app\teacher\controller\core;

use app\common\controller\Frontend;
use app\common\enums\TcScheduleStatusEnum;
use app\common\enums\TrialClassOrderStatusEnum;
use app\common\model\banxi\core\CoreTrialClassOrder as CoreTrialClassOrderModel;


/*
 * 排课预约
 * */

class CoreTrialClassOrder extends Frontend
{
    protected array $noNeedLogin = [''];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    //分页-抢单中心
    public function listGrabTrialClassOrderPage()
    {
        $params = $this->request->param(['index', 'limit', 'searchText']);
        $coreTrialClassOrderModel = new CoreTrialClassOrderModel();
        $query = $coreTrialClassOrderModel->where([
            'scheduleStatus' => TcScheduleStatusEnum::E2,
        ]);
        if ($params['searchText']) {
            $searchText = $params['searchText'];
            $query = $query->alias('a')->whereExists(function ($query) use ($searchText) {
                $query->name('banxi_student')
                    ->whereColumn('a.studentId', 'id')
                    ->where('name', 'like', '%' . $searchText . '%')
                    ->where('del', 0);

            });
        }
        $pageParams = get_page_params($params);
        $list = $query->order(['id' => 'desc'])->paginate([
            'page' => $pageParams['page'],
            'list_rows' => $pageParams['limit'],
        ]);
        $this->ok('操作成功', result_row($list));
    }

    //抢单
    public function grabOrder()
    {
        $params = $this->request->param(['orderId']);
        $coreTrialClassOrderModel = new CoreTrialClassOrderModel();

        // 获取当前教练ID
        $trainerId = $this->auth->getUserInfo()['id'];

        // 使用一条SQL语句完成查询和更新，避免并发问题
        $res = $coreTrialClassOrderModel->where([
            'id' => $params['orderId'],
            'orderStatus' => TrialClassOrderStatusEnum::SUCCESS_PAY,
            'scheduleStatus' => TcScheduleStatusEnum::E2
        ])->update([
            'trainerId' => $trainerId,
            'scheduleStatus' => TcScheduleStatusEnum::E3
        ]);

        if (!$res) {
            // 根据具体情况返回不同的错误信息
            $classOrder = $coreTrialClassOrderModel->where(['id' => $params['orderId']])->find();
            if (empty($classOrder)) {
                $this->fail('订单不存在');
            } elseif ($classOrder['orderStatus'] != TrialClassOrderStatusEnum::SUCCESS_PAY) {
                $this->fail('订单状态不正确');
            } elseif ($classOrder['scheduleStatus'] != TcScheduleStatusEnum::E2) {
                $this->fail('订单已排课');
            } else {
                $this->fail('抢单失败，请刷新');
            }
        }

        $this->ok('抢单成功');
    }
}